package com.talkology.pilot.student.service.impl;

import com.talkology.pilot.database.dao.WxGroupMapper;
import com.talkology.pilot.database.model.WxGroup;
import com.talkology.pilot.student.service.IWxGroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

@Service
public class WxGroupServiceImpl implements IWxGroupService {
    private static final Logger LOG = LoggerFactory.getLogger(WxGroupServiceImpl.class);

    @Autowired
    private WxGroupMapper mapper;

    @Override
    public List<WxGroup> getAllByFilter(Integer useFlag, String userName) {
        return mapper.getAllByFilter(useFlag, userName);
    }

    @Override
    @Transactional
    public WxGroup getInfo(Integer index) {
        return mapper.selectByPrimaryKey(index);
    }

    @Override
    @Transactional
    public void add(WxGroup record) {
        mapper.insert(record);
    }

    @Override
    @Transactional
    public void edit(WxGroup record) {
        if (record.getUseFlag() == 1) {
            throw new RuntimeException("Already occupied cannot be modified");
        }
        mapper.updateByPrimaryKey(record);
    }

    @Override
    @Transactional
    public void delete(Integer index) {
        WxGroup record = mapper.selectByPrimaryKey(index);
        if (record.getUseFlag() == 1) {
            throw new RuntimeException("Already occupied cannot be deleted");
        }
        mapper.deleteByPrimaryKey(index);
    }

    @Override
    @Transactional
    public synchronized String occupyNewOne(String studentId) {
        List<WxGroup> wxGroupOld = mapper.getAllByFilter(1, studentId);
        if (wxGroupOld != null && wxGroupOld.size() != 0) {
            throw new RuntimeException("This student already has one wx group");
        }
        WxGroup wxGroupNew = mapper.selectNewOne();
        wxGroupNew.setUseFlag(1);
        wxGroupNew.setUserName(studentId);
        mapper.updateByPrimaryKey(wxGroupNew);
        return wxGroupNew.getImageUrl();
    }

    @Override
    @Transactional
    public void batchImport(MultipartFile profile) {
        if (!profile.getOriginalFilename().endsWith(".txt")) {
            throw new RuntimeException("Please input a txt file.");
        }
        List<WxGroup> groupList = mapper.getAllByFilter(0, null);
        groupList.forEach(g -> {
            g.setUseFlag(-1);
            mapper.updateByPrimaryKey(g);
        });
        InputStream inputStream = null;
        try {
            inputStream = profile.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            reader.lines().forEach(l -> {
                if (l.contains("http")) {
                    WxGroup g = new WxGroup();
                    g.setUseFlag(0);
                    g.setImageUrl(l);
                    String n = l.replace("http://classroom.talkology.cn/", "")
                            .replace(".jpeg", "");
                    g.setGroupName(n);
                    g.setCreateTime(new Date());
                    g.setUserName("");
                    mapper.insert(g);
                }
            });
        } catch (IOException e) {
            LOG.error("{}", e);
        } finally {
            try {
                assert inputStream != null;
                inputStream.close();
            } catch (IOException e) {
                LOG.error("{}", e);
            }
        }
    }
}
